package com.hontech.libratest.activity

import android.content.pm.PackageManager
import android.view.MotionEvent
import androidx.appcompat.app.AppCompatActivity
import com.hontech.libratest.utils.hideSoftKey
import kotlinx.coroutines.CompletableDeferred

open class BaseActivity : AppCompatActivity() {

    companion object {
        private const val PERMISSION_CODE = 1
    }

    private var permissionFuture: CompletableDeferred<Boolean>? = null

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if ((grantResults.size == 1) && (requestCode == PERMISSION_CODE)) {
            val ret = grantResults[0] == PackageManager.PERMISSION_GRANTED
            permissionFuture?.complete(ret)
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    suspend fun requestPermission(name: String): Boolean {
        val ret = checkSelfPermission(name) == PackageManager.PERMISSION_GRANTED
        if (ret) {
            return true
        }
        permissionFuture = CompletableDeferred<Boolean>()
        requestPermissions(arrayOf(name), PERMISSION_CODE)
        return permissionFuture!!.await()
    }

    override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
        if (ev.action == MotionEvent.ACTION_DOWN) {
            hideSoftKey(this)
        }
        return super.dispatchTouchEvent(ev)
    }
}

